<?php
namespace app\forms;

use yii\base\Model;
use app\models\User;
use app\forms\exceptions\LoginFailedException;
use app\forms\exceptions\ParamNotValidateException;

class UserLoginForm extends Model {
	const SCENARIO_LOGIN = 'login';
	
	public $username;
	public $password;
	
	public function rules() {
		return [
			[['username', 'password'], 'required']
		];
	}
	
	public function scenarios() {
		return [
			self::SCENARIO_LOGIN => ['username', 'password']
		];
	}
	
	public function login() {
		if (!$this->validate()) {
			throw new ParamNotValidateException($this);
		}
		
		$user = User::findByUsername($this->username);
		if (!empty($user)) {
			if (\Yii::$app->security->validatePassword($this->password, $user->password)) {
				return $user;
			} else {
				throw new LoginFailedException(LoginFailedException::PASSWORD_NOT_MATCH);
			}
		} else {
			throw new LoginFailedException(LoginFailedException::USER_NOT_EXIST);
		}
	}
}